// src/utils/paramParser.js
class ParamParser {
  /**
   * 生成参数名称和模板code的对照表（使用下划线表示数组索引）
   */
  static generateParamMapping(projectConfig) {
    const mapping = new Map();
    
    // 添加基本信息字段
    this.addBasicInfoMapping(mapping);
    
    if (projectConfig.paramGroups) {
      projectConfig.paramGroups.forEach(group => {
        this.parseGroupParams(group, mapping);
      });
    }
    
    return Array.from(mapping.entries()).reverse().map(([code, item]) => ({
      paramName: item.name,
      paramCode: code,
      required: item.required,
      templateVariable: `\${${code}}`
    }));
  }

  /**
   * 添加基本信息字段映射
   */
  static addBasicInfoMapping(mapping) {
    mapping.set('sampleNo', { name: '样品编号', required: true });
    mapping.set('projectId', { name: '项目ID', required: true });
    mapping.set('projectName', { name: '项目名称', required: true });
    mapping.set('standardCode', { name: '标准规范', required: true });
    mapping.set('timestamp', { name: '检测时间', required: true });
  }

  /**
   * 递归解析参数组
   */
  static parseGroupParams(group, mapping) {
    const isDynamicTable = group.allowDynamicRows === true;

    // 1. 先处理子组
    if (group.childGroups) {
      group.childGroups.forEach(childGroup => {
        const isChildDynamicTable = childGroup.allowDynamicRows === true;
        this.parseChildGroupParams(childGroup, mapping, isChildDynamicTable);
      });
    }

    // 2. 再处理当前组
    if (group.paramItems) {
      group.paramItems.forEach(param => {
        this.addParamToMapping(param, mapping, isDynamicTable, group.maxRows);
      });
    }
  }

  /**
   * 递归解析子组参数
   */
  static parseChildGroupParams(group, mapping, isDynamicTable) {
    // 先处理孙子组
    if (group.childGroups) {
      group.childGroups.forEach(childGroup => {
        const isGrandChildDynamicTable = childGroup.allowDynamicRows === true;
        this.parseChildGroupParams(childGroup, mapping, isGrandChildDynamicTable);
      });
    }

    // 再处理当前子组
    if (group.paramItems) {
      group.paramItems.forEach(param => {
        this.addParamToMapping(param, mapping, isDynamicTable, group.maxRows);
      });
    }
  }

  /**
   * 添加参数到对照表（使用下划线表示数组索引）
   */
  static addParamToMapping(param, mapping, isDynamicTable, maxRows = 3) {
    const paramName = param.paramName;
    const paramCode = param.paramCode;
    const isRequired = param.validateRule && param.validateRule.required === true;
    
    // 如果是多测次参数 (multiMeasureCount > 1)
    if (param.isMultiMeasure && param.multiMeasureCount > 1) {
      if (isDynamicTable) {
        // 动态表格中的多测次参数：只生成行数据
        for (let rowIndex = 0; rowIndex < maxRows; rowIndex++) {
          for (let i = 0; i < param.multiMeasureCount; i++) {
            const rowIndexedCode = `row_${rowIndex + 1}.${paramCode}_${i + 1}`;
            const rowIndexedName = `${paramName}[第${i + 1}测次] - 第${rowIndex + 1}行`;
            mapping.set(rowIndexedCode, { name: rowIndexedName, required: isRequired });
          }
        }
      } else {
        // 非动态表格中的多测次参数：只生成基础数据
        for (let i = 0; i < param.multiMeasureCount; i++) {
          const indexedCode = `${paramCode}_${i + 1}`;
          const indexedName = `${paramName}[${i + 1}]`;
          mapping.set(indexedCode, { name: indexedName, required: isRequired });
        }
      }
    } else {
      // 单测次参数 (multiMeasureCount = 1 或 undefined)
      if (isDynamicTable) {
        // 动态表格中的单测次参数：只生成行数据
        for (let i = 0; i < maxRows; i++) {
          const rowCode = `row_${i + 1}.${paramCode}`;
          const rowName = `${paramName} - 第${i + 1}行`;
          mapping.set(rowCode, { name: rowName, required: isRequired });
        }
      } else {
        // 非动态表格中的单测次参数：生成基础数据
        mapping.set(paramCode, { name: paramName, required: isRequired });
      }
    }
  }

  /**
   * 生成Markdown格式的对照表
   */
  static generateMarkdownMapping(projectConfig) {
    const mapping = this.generateParamMapping(projectConfig);
    let markdown = '# 参数名称与Code编码对照表\n\n';
    markdown += '| 参数名称 | Code编码 | 是否必填 | 模板变量 |\n';
    markdown += '|----------|----------|----------|----------|\n';
    
    mapping.forEach(item => {
      const requiredText = item.required ? '是' : '否';
      markdown += `| ${item.paramName} | ${item.paramCode} | ${requiredText} | \${${item.paramCode}} |\n`;
    });
    
    return markdown;
  }

  /**
   * 生成CSV格式的对照表
   */
  static generateCsvMapping(projectConfig) {
    const mapping = this.generateParamMapping(projectConfig);
    let csv = '参数名称,Code编码,是否必填,模板变量\n';
    
    mapping.forEach(item => {
      const requiredText = item.required ? '是' : '否';
      csv += `${item.paramName},${item.paramCode},${requiredText},\${${item.paramCode}}\n`;
    });
    
    return csv;
  }

  /**
   * 获取必填参数统计
   */
  static getRequiredStats(projectConfig) {
    const mapping = this.generateParamMapping(projectConfig);
    const total = mapping.length;
    const required = mapping.filter(item => item.required).length;
    const optional = total - required;
    
    return {
      total,
      required,
      optional,
      requiredPercentage: total > 0 ? ((required / total) * 100).toFixed(1) : 0
    };
  }

  /**
   * 导出对照表文件
   */
  static exportMapping(projectConfig, format = 'markdown') {
    let content, filename, mimeType;
    
    switch (format) {
      case 'markdown':
        content = this.generateMarkdownMapping(projectConfig);
        filename = '参数对照表.md';
        mimeType = 'text/markdown';
        break;
      case 'csv':
        content = this.generateCsvMapping(projectConfig);
        filename = '参数对照表.csv';
        mimeType = 'text/csv';
        break;
      case 'json':
        content = JSON.stringify(this.generateParamMapping(projectConfig), null, 2);
        filename = '参数对照表.json';
        mimeType = 'application/json';
        break;
      default:
        throw new Error('不支持的格式');
    }
    
    // 创建Blob并下载
    const blob = new Blob([content], { type: mimeType });
    const url = URL.createObjectURL(blob);
    const link = document.createElement('a');
    link.href = url;
    link.download = filename;
    document.body.appendChild(link);
    link.click();
    document.body.removeChild(link);
    URL.revokeObjectURL(url);
  }
}

// 确保正确导出
export default ParamParser;